package com.application.fabric.users.config.encryptAl;

import org.hyperledger.fabric.gateway.Wallet;
import org.hyperledger.fabric.gateway.Wallets;
import org.hyperledger.fabric.gateway.X509Identity;
import org.hyperledger.fabric.sdk.security.CryptoSuite;
import org.hyperledger.fabric.sdk.security.CryptoSuiteFactory;
import org.hyperledger.fabric_ca.sdk.HFCAClient;
import org.springframework.stereotype.Repository;
import java.security.PrivateKey;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.nio.file.Paths;
import java.security.cert.X509Certificate;
import java.util.Base64;
import java.util.Properties;

@Repository
public class ReadKey {
    public String readwallet(String useid) throws Exception{
        BufferedReader reader = new BufferedReader(new FileReader(new File("src/main/java/com/application/fabric/fabriccontrol/wallet/"+useid)));
        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
        reader.close();
        return line;
    }
    public String Certificatemsg(String Userid ) throws Exception{
        Properties props = new Properties();
        props.put("pemFile","src/main/resources/crypto-config/peerOrganizations/org1.example.com/ca/ca.org1.example.com-cert.pem");
        props.put("allowAllHostNames","true");
        HFCAClient caClient = HFCAClient.createNewInstance("https://localhost:7054", props);
        CryptoSuite cryptoSuite = CryptoSuiteFactory.getDefault().getCryptoSuite();
        caClient.setCryptoSuite(cryptoSuite);
        Wallet wallet = Wallets.newFileSystemWallet(Paths.get("src/main/java/com/application/fabric/fabriccontrol/wallet"));
        X509Identity UserIdentity = (X509Identity)wallet.get(Userid);
        X509Certificate cer = UserIdentity.getCertificate();
        return Base64.getEncoder().encodeToString(cer.getEncoded());
    }

    public String PrivateKeymsg(String Userid) throws Exception{
        Properties props = new Properties();
        props.put("pemFile","src/main/resources/crypto-config/peerOrganizations/org1.example.com/ca/ca.org1.example.com-cert.pem");
        props.put("allowAllHostNames","true");
        HFCAClient caClient = HFCAClient.createNewInstance("https://localhost:7054", props);
        CryptoSuite cryptoSuite = CryptoSuiteFactory.getDefault().getCryptoSuite();
        caClient.setCryptoSuite(cryptoSuite);
        Wallet wallet = Wallets.newFileSystemWallet(Paths.get("src/main/java/com/application/fabric/fabriccontrol/wallet"));
        X509Identity UserIdentity = (X509Identity)wallet.get(Userid);
        PrivateKey prikey = UserIdentity.getPrivateKey();
//        String key = Base64.getEncoder().encodeToString(prikey.getEncoded());
        return Base64.getEncoder().encodeToString(prikey.getEncoded());
    }
}
